const { getNavList, getNavDetail, addNav, updateNav, deleteNav } = require('../controller/nav')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const { transTree } = require('../utils/helper')

const handleNavRouter = (req, res) => {
  // 导航列表
  if (req.method === 'GET' && req.path === '/api/nav/list') {
    return getNavList(req.query).then(data => {
      if (data) {
        const list = transTree(data, 'nid', 'pid')
        return new SuccessModel(list)
      } else {
        return new ErrorModel(data)
      }
    })
  }

  // 导航详情
  if (req.method === 'GET' && req.path === '/api/nav/detail') {
    return getNavDetail(req.query).then(data => {
      if (data) {
        return new SuccessModel(data)
      } else {
        return new ErrorModel(data)
      }
    })
  }

  // 添加导航
  if (req.method === 'POST' && req.path === '/api/nav/add') {
    return addNav(req.body).then(data => {
      if (data) {
        return new SuccessModel({}, '添加成功')
      } else {
        return new ErrorModel({}, '添加失败')
      }
    })
  }

  // 更新导航
  if (req.method === 'POST' && req.path === '/api/nav/update') {
    return updateNav(req.body).then(data => {
      if (data) {
        return new SuccessModel({}, '添加成功')
      } else {
        return new ErrorModel({}, '添加失败')
      }
    })
  }

  // 删除导航
  if (req.method === 'POST' && req.path === '/api/nav/delete') {
    return deleteNav(req.body).then(data => {
      if (data) {
        return new SuccessModel({}, '删除成功')
      } else {
        return new ErrorModel({}, '删除失败')
      }
    })
  }
}

module.exports = handleNavRouter
